/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.jprvyd.gui.form;

import cz.muni.fi.pb138.jprvyd.Invoice;
import cz.muni.fi.pb138.jprvyd.Item;
import cz.muni.fi.pb138.jprvyd.gui.model.Item_TableModel;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

/**
 *
 * @author Jan
 */
public class ItemForm extends javax.swing.JFrame {

    InvoiceForm invoiceForm;
    Invoice invoice;
    Item item;
    static boolean ADD = true;
    static boolean EDIT = false;
    boolean choice;

    /**
     * Creates new form ItemForm
     */
    public ItemForm() {
        this.invoiceForm = new InvoiceForm();
        this.invoice = new Invoice();
        initComponents();
    }

    public ItemForm(InvoiceForm invoiceForm, Invoice invoice) {
        this.invoiceForm = invoiceForm;
        this.invoice = invoice;
        choice = ADD;
        initComponents();
    }

    public ItemForm(InvoiceForm invoiceForm, Invoice invoice, Item item) {
        this.invoiceForm = invoiceForm;
        this.invoice = invoice;
        this.item = item;
        initComponents();
        textFieldName.setText(item.getName());
        textFieldQuantity.setText(new Integer(item.getQuantity()).toString());
        textFieldUnit.setText(item.getUnit());
        textFieldUnitPrice.setText(new Integer(item.getUnitPrice()).toString());
        choice = EDIT;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField4 = new javax.swing.JTextField();
        labelName = new javax.swing.JLabel();
        labelQuantity = new javax.swing.JLabel();
        labelUnit = new javax.swing.JLabel();
        labelUnitPrice = new javax.swing.JLabel();
        textFieldUnitPrice = new javax.swing.JTextField();
        textFieldUnit = new javax.swing.JTextField();
        textFieldName = new javax.swing.JTextField();
        textFieldQuantity = new javax.swing.JTextField();
        buttonSave = new javax.swing.JButton();
        buttonCancel = new javax.swing.JButton();

        jTextField4.setText("jTextField4");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("JPrVyd - Managing items");

        labelName.setText("Name:");

        labelQuantity.setText("Quantity:");

        labelUnit.setText("Unit:");

        labelUnitPrice.setText("Unit price:");

        buttonSave.setText("Save");
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        buttonCancel.setText("Cancel");
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelUnitPrice)
                            .addComponent(labelUnit)
                            .addComponent(labelName)
                            .addComponent(labelQuantity))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textFieldQuantity)
                            .addComponent(textFieldName)
                            .addComponent(textFieldUnit)
                            .addComponent(textFieldUnitPrice)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(buttonSave, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 108, Short.MAX_VALUE)
                        .addComponent(buttonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelName)
                    .addComponent(textFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(labelQuantity)
                            .addComponent(textFieldQuantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(labelUnit))
                    .addComponent(textFieldUnit, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textFieldUnitPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelUnitPrice))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSave)
                    .addComponent(buttonCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed
        boolean ok = false;
        String name = textFieldName.getText();
        String unit = textFieldUnit.getText();
        String quantityString = textFieldQuantity.getText();
        String unitPriceString = textFieldUnitPrice.getText();
        int quantity = 0;
        int unitPrice = 0;
        if (name.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter item name");
        } else if (quantityString.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter quantity");
        } else if (unit.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter unit type");
        } else if (unitPriceString.equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Enter unit price");
        } else {
            ok = true;
            try {
                quantity = Integer.parseInt(quantityString);
            } catch (NumberFormatException e) {
                ok = false;
                JOptionPane.showMessageDialog(rootPane, "Quantity must be a number");
            }
            try {
                unitPrice = Integer.parseInt(unitPriceString);
            } catch (NumberFormatException e) {
                ok = false;
                JOptionPane.showMessageDialog(rootPane, "Unit price must be a number");
            }
        }
        if (ok) {

            if (choice == ADD) {
                item = new Item();
                item.setName(name);
                item.setQuantity(quantity);
                item.setUnitPrice(unitPrice);
                item.setUnit(unit);

                List<Item> itemsUnmodifiable = invoiceForm.invoice.getItems();
                ArrayList<Item> items = new ArrayList<Item>();
                for (Item it : itemsUnmodifiable) {
                    items.add(it);
                    if (it.getName().equals(name)) {
                        JOptionPane.showMessageDialog(rootPane, "Item '" + name + "' already exists");
                        item = null;
                    }
                }
                if (item != null) {
                    buttonSave.setEnabled(false);
                    items.add(item);
                    invoiceForm.invoice.setItems(items);
                    Item_TableModel model = (Item_TableModel) invoiceForm.tableItems.getModel();
                    model.addItem(item);
                    this.dispose();
                }

            } else if (choice == EDIT) {
                if (item.getName().equals(name)
                        && item.getQuantity() == quantity
                        && item.getUnit().equals(unit)
                        && item.getUnitPrice() == unitPrice) {
                    // nothing to change
                    this.dispose();
                } else {
                    buttonSave.setEnabled(false);
                    String formerName = item.getName();
                    item.setName(name);
                    item.setQuantity(quantity);
                    item.setUnit(unit);
                    item.setUnitPrice(unitPrice);

                    List<Item> items = invoice.getItems();
                    for (Item it : items) {
                        if (it.getName().equals(formerName)) {
                            it = item;
                        }
                    }
                    invoiceForm.invoice.setItems(items);
                    invoiceForm.tableItems.updateUI();
                    this.dispose();
                }
            }
        }
    }//GEN-LAST:event_buttonSaveActionPerformed

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_buttonCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ItemForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ItemForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ItemForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ItemForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ItemForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonSave;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JLabel labelName;
    private javax.swing.JLabel labelQuantity;
    private javax.swing.JLabel labelUnit;
    private javax.swing.JLabel labelUnitPrice;
    private javax.swing.JTextField textFieldName;
    private javax.swing.JTextField textFieldQuantity;
    private javax.swing.JTextField textFieldUnit;
    private javax.swing.JTextField textFieldUnitPrice;
    // End of variables declaration//GEN-END:variables
}
